/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.uniceub.fsw.agenda.model.facade;

import br.uniceub.fsw.agenda.exception.DatabaseException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 * Facade generico do qual todos os outros facades serao "extendidos".
 * Metodos para abrir e fechar conexao serao implementados aqui.
 * 
 * 05/04/2008
 * @author Rodrigo Uchôa - rodrigo.uchoa@yahoo.com
 *
 */
public class GenericFacade {
    protected Connection con;
   
    
    public GenericFacade() {}
    
    /**
     * Método que abre conexao com o banco de dados. Datasource do tomcat será
     * usado.
     * Observe que o datasource tem que ser configurado no arquivo context.xml
     * 
     * Para mais detalhes LEIA a documentacao do tomcat no capitulo:
     * JNDI DataSources HOW-TO
     * 
     * @return objeto Connection.
     */
    protected Connection getConnection() throws DatabaseException {
        try {             
            Context ctx = new InitialContext();
            //fazer lookup do datasource declarado no context.xml            
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/MySQLDataSource");
            this.con = ds.getConnection();                
            return this.con;                    
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new DatabaseException("Erro no datasource", ex);
        }
        
    }
    
    protected void closeConnection() {
        try {
            if (this.con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
